package com.briup.ptt.web.interceptor;

import com.briup.ptt.exception.CustomException;
import com.briup.ptt.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 杰瑞
 * @date 2025/8/15
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    /**
     * 预处理
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token = request.getHeader("token");
        if(token == null){
            throw new CustomException("用户未登录，请登录后再访问");
        }

        try {
            JWTUtil.verify(token);
        } catch (Exception e) {
            throw new CustomException("token无效，请重新登录");
        }
        return true;

    }

}
